package com.quality.web.server.db;

import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public final class DaoConfig {

  private static final Logger logger = Logger.getLogger(DaoConfig.class);

  private DaoConfig() {
  }

  private static final String RESOURCE = "com/quality/web/server/db/dao.xml";
  private static final String PROPS_DEFAULT = "database.properties";
  private static final SqlMapClient SQL_CLIENT = getManagerDAO();

  private static SqlMapClient getManagerDAO() {
    try {
      Properties props = getPropertiesFile();
      final Reader reader = Resources.getResourceAsReader(RESOURCE);
      return SqlMapClientBuilder.buildSqlMapClient(reader, props);
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }

  private static Properties getPropertiesFile() throws IOException {
    Properties props = new Properties();
    String computerName = System.getenv("COMPUTERNAME");
    computerName = computerName.toLowerCase();
    Reader propsReader;
    try {
      propsReader = Resources.getResourceAsReader(PROPS_DEFAULT + "."
          + computerName);
      props.load(propsReader);
      return props;
    } catch (IOException e) {
      logger.info("Doesn't exists :" + PROPS_DEFAULT + "." + computerName + " ");
    }
    logger.info("using default database config file");
    propsReader = Resources.getResourceAsReader(PROPS_DEFAULT);
    props.load(propsReader);
    return props;
  }

  public static SqlMapClient getSqlMapClient() {
    return SQL_CLIENT;
  }

}
